/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.dialog.io.controller;

import java.awt.Cursor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import offset.nodes.client.dialog.io.view.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ResourceBundle;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
import offset.nodes.client.dialog.io.model.ExportBook;
import offset.nodes.client.model.ServerModel;
import offset.nodes.client.model.ServerResponse;
import offset.nodes.client.dialog.io.model.ExportData;
import offset.nodes.client.dialog.io.model.ExportNode;
import offset.nodes.client.dialog.io.model.GetDataSize;
import offset.nodes.client.view.BaseApplet;
import offset.nodes.client.view.ProgressDialog;

/**
 *
 * @author Walter Lütgenau
 */
public class ExportApplet extends BaseApplet implements PropertyChangeListener {

    JFileChooser dialog = null;
    ServerModel model = null;
    String fromPath = null;
    ProgressDialog progress = null;
    ResourceBundle bundle = ResourceBundle.getBundle("offset/nodes/client/dialog/view/DialogBundle");

    /** Creates a new instance of NodeChooserApplet */
    public ExportApplet() {
    }

    public void startUI() {
        int result = dialog.showDialog(new JFrame(), bundle.getString("export.title"));
        URL path = null;
        try {
            if (result == JFileChooser.APPROVE_OPTION) {
                File selected = dialog.getSelectedFile();
                ExportPanel export = (ExportPanel) dialog.getAccessory();

                ExportNode.Request exportNodeRequest = new ExportNode.Request();
                exportNodeRequest.setIgnoreBinary(export.skipBinary());
                exportNodeRequest.setRecursive(export.recurseIntoSubfolders());
                exportNodeRequest.setPath(fromPath);

                progress = new ProgressDialog(null, true);
                progress.getProgressBar().setIndeterminate(true);
                progress.setLocationByPlatform(true);

                setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                Task task = new Task(selected, exportNodeRequest);
                task.addPropertyChangeListener(this);
                task.execute();

                progress.setVisible(true);
            }

            path = new URL(getParameter("repository") + "/" + fromPath);

        } catch (Exception e) {
            e.printStackTrace();
        }

        getAppletContext().showDocument(path);
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if ("progress" == evt.getPropertyName()) {
            int current = (Integer) evt.getNewValue();
            if (progress.getProgressBar().isIndeterminate()) {
                progress.getProgressLabel().setText(bundle.getString("data.fetchingData"));
                progress.getProgressBar().setMaximum(100);
                progress.getProgressBar().setValue(current);
                progress.getProgressBar().setIndeterminate(false);
            } else
                progress.getProgressBar().setValue(current);
            if (current == 100)
                progress.setVisible(false);
        }
    }

    class Task extends SwingWorker<Void, Void> {

        File selected;
        ExportNode.Request exportNodeRequest;

        public Task(File selected, ExportNode.Request exportNodeRequest) {
            this.selected = selected;
            this.exportNodeRequest = exportNodeRequest;
        }

        @Override
        protected Void doInBackground() throws Exception {
            ExportNode.Response exportNodeResponse = (ExportNode.Response) model.sendRequest(exportNodeRequest);
            if (exportNodeResponse.getResult() == ServerResponse.RESULT_SUCCESS) {
                GetDataSize.Request getDataSizeRequest = new GetDataSize.Request();
                getDataSizeRequest.setDataId(exportNodeResponse.getExportId());

                GetDataSize.Response getDataSizeResponse = (GetDataSize.Response) model.sendRequest(getDataSizeRequest);

                setProgress(0);

                OutputStream out = new FileOutputStream(selected);
                ExportData.Request exportDataRequest = new ExportData.Request();

                boolean goOn = true;
                int count = 0;
                do {
                    exportDataRequest.setDataId(exportNodeResponse.getExportId());

                    ExportData.Response exportDataResponse = (ExportData.Response) model.sendRequest(exportDataRequest);
                    if (exportDataResponse.getResult() == ServerResponse.RESULT_SUCCESS) {
                        out.write(exportDataResponse.getData());
                        count += exportDataResponse.getData().length;
                    }
                    if (exportDataResponse.isLastFragment())
                        goOn = false;

                    setProgress((int) (100 * count / getDataSizeResponse.getSize()));
                } while (goOn);

                out.close();
            }

            return null;
        }
    }

    @Override
    public void initUI() {
        try {
            fromPath = getParameter("path");
            String url = getParameter("service");

            model = new ServerModel(new URL(url));
            dialog = new JFileChooser();
            dialog.setAccessory(new ExportPanel());
            dialog.setDialogType(JFileChooser.SAVE_DIALOG);
            dialog.setSelectedFile(new File(new File(fromPath).getName() + ".xml"));
            dialog.setLocation(100, 100);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
